package server

import (
	"common/database/config"
	"context"
	"errors"
	"gorm.io/gorm"
	"shop_srv/internal/models/dao"
	"shop_srv/internal/models/service"
	pb "shop_srv/proto"
)

type Server struct {
	pb.UnimplementedShopServer
}

func (c *Server) Create(ctx context.Context, request *pb.CreateRequest) (*pb.CreateResponse, error) {
	shop := dao.Shop{
		ShopName:       request.ShopName,
		ShopAddress:    request.ShopAddress,
		ShopImage:      request.ShopImage,
		ShopType:       int(request.ShopType),
		ShopMessage:    request.ShopMessage,
		ShopMain:       request.ShopMain,
		PeopleBuyPrice: float64(request.PeopleBuyPrice),
		StartingBuy:    float64(request.StartingBuy),
		ShopPaper:      request.ShopPaper,
		ShopMath:       request.ShopMath,
		ShopClassId:    int(request.ShopClassId),
	}
	err := config.DB.Create(&shop).Error

	if err != nil {
		return nil, errors.New("商品添加失败")
	}
	service.ShopCreate(shop, int(shop.ID))
	return &pb.CreateResponse{Id: int64(shop.ID)}, nil
}

func (c *Server) List(ctx context.Context, request *pb.ListRequest) (*pb.ListResponse, error) {
	var shop []*dao.Shop
	var sli []*pb.Shops
	if request.KeyWord != "" {
		config.DB.Where("shop_name=? or shop_address=? or shop_main=?", request.KeyWord).Scopes(Paginate(int(request.Page), int(request.PageSize))).Find(&shop)
		for _, d := range shop {
			one := &pb.Shops{
				ShopName:       d.ShopName,
				ShopAddress:    d.ShopAddress,
				ShopImage:      d.ShopImage,
				ShopType:       int64(d.ShopType),
				ShopMessage:    d.ShopMessage,
				ShopMain:       d.ShopMain,
				PeopleBuyPrice: float32(d.PeopleBuyPrice),
				StartingBuy:    float32(d.StartingBuy),
				ShopPaper:      d.ShopPaper,
				ShopMath:       d.ShopMath,
				ShopClassId:    int64(d.ShopClassId),
			}
			sli = append(sli, one)
		}
	} else {
		config.DB.Scopes(Paginate(int(request.Page), int(request.PageSize))).Find(&shop)
		for _, d := range shop {
			one := &pb.Shops{
				ShopName:       d.ShopName,
				ShopAddress:    d.ShopAddress,
				ShopImage:      d.ShopImage,
				ShopType:       int64(d.ShopType),
				ShopMessage:    d.ShopMessage,
				ShopMain:       d.ShopMain,
				PeopleBuyPrice: float32(d.PeopleBuyPrice),
				StartingBuy:    float32(d.StartingBuy),
				ShopPaper:      d.ShopPaper,
				ShopMath:       d.ShopMath,
				ShopClassId:    int64(d.ShopClassId),
			}
			sli = append(sli, one)
		}
	}
	return &pb.ListResponse{Shop: sli}, nil
}

func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {

		if page <= 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}
